package com.myself.ssoserver.controller

import com.myself.common.page.Page
import com.myself.common.page.PageResult
import com.myself.ssoserver.entity.Nomination
import com.myself.ssoserver.entity.TriLottery
import com.myself.ssoserver.service.NominationService
import com.myself.ssoserver.service.TriLotteryService
import com.myself.ssoserver.service.UserService
import org.ktorm.dsl.and
import org.ktorm.dsl.eq
import org.springframework.transaction.annotation.Transactional
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController


@RequestMapping("/nomination")
@RestController
open class NominationController(
    private val nominationService: NominationService,
    private val userService: UserService,
    private val triLotteryService: TriLotteryService
) {
    @PostMapping("/findAll")
    open fun searchAll(@RequestBody page: Page): PageResult<Nomination> {
        return nominationService.findAll(page)
    }

    @PostMapping("/find")
    open fun search(@RequestBody page: Page): PageResult<Nomination> {
        val currentUser = userService.getCurrentUser()
        return nominationService.findPageListBy(page) { it.userId eq currentUser.id }
    }

    @PostMapping("/calAndNew")
    @Transactional
    open fun calAndNew() {
        val calculateTotalPrice = triLotteryService.calculateTotalPrice()
        nominationService.updateOrSave(calculateTotalPrice)
    }

    @PostMapping("/getTriLotteryListById")
    open fun getTriLotteryListById( @RequestBody page: Page): PageResult<TriLottery> {
        val nomination = page.id?.let { nominationService.findById(it) } ?: throw IllegalStateException("单据信息没找到")
        val currentUser = userService.getCurrentUser()
        return triLotteryService.findPageListBy(page) { (it.userId eq currentUser.id) and (it.versionId eq nomination.version.id)}
    }

}